<?php
/**
 * 后台customer权限下，设备账号的管理
 *
 * Author: lyun
 * Date: 2018/6/28
 * Created by Panxsoft.
 */


namespace App\Http\Controllers\Admin\Customer;

use App\Exceptions\ApiAbstractException;
use App\Http\Controllers\ApiController;
use App\Http\Middleware\AdminAuth;
use App\Http\Middleware\CustomerAuth;
use App\Http\Requests\Admin\Customer\Device\DeviceAccountPatchEnabledRequest;
use App\Http\Requests\Admin\Customer\Device\DeviceAccountStoreRequest;
use App\Http\Requests\Admin\Customer\Device\DeviceAccountUpdateRequest;
use App\Http\Requests\Admin\Customer\DeviceAccountIndexRequest;
use App\Models\Admin\CustomerAdmin;
use App\Models\Customer\Customer;
use App\Models\Customer\DeviceAccount;
use App\Models\Panx\SkinDetector;
use App\Models\Store\Store;
use App\Services\Utils\Guard;
use Illuminate\Http\Request;

class DeviceAccountController extends ApiController
{
    const ROUTES = [
        'index'  => 'api.admin.customer.device.account.index',
        'store'  => 'api.admin.customer.device.account.store',
        'update' => 'api.admin.customer.device.account.update',
        'patch'  => 'api.admin.customer.device.account.patch',
    ];

    /**
     * 普通客户 和 购买软件的客户 展示设备账号的列表
     * @test
     *
     * @param DeviceAccountIndexRequest $request
     *
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function index(DeviceAccountIndexRequest $request)
    {
        // 超管才能操作的
        $this->checkIsTrue(CustomerAdmin::isGuardSuperAdmin(), trans('admin.is_super_man'));

        /** @var Customer $customer */
        $customer = Guard::customer();

        $this->checkIsTrue(
            ! $customer->isProviderType(Customer::PROVIDER_TYPE_VIRTUAL),
            trans('admin.is_virtual_provider')
        );

        $device_accounts = $customer->deviceAccounts()
            ->columnsKeywordsOrLike([
                'device_name' => $request->keyword,
                'account' => $request->keyword,
            ])
            ->with('store')
            ->latest()
            ->paginate($request->per_page?:15);

        return $this->response(compact('device_accounts'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        // 返回客户的下级店铺stores
        $stores = Guard::customer()
            ->stores()
            ->where('is_deleted', Store::IS_NOT_DELETED)
            ->get();

        //返回肤质检测仪的信息
        $skin_detectors = SkinDetector::all();

        return $this->response(compact('stores', 'skin_detectors'));
    }
    
    /**
     * 购买软件的客户，添加设备账号
     * @test
     *
     * @param  DeviceAccountStoreRequest $request
     *
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function store(DeviceAccountStoreRequest $request)
    {
        // 超管才能操作的
        $this->checkIsTrue(CustomerAdmin::isGuardSuperAdmin(), trans('admin.is_super_man'));

        // 检测是否是购买软件的客户
        /** @var Customer $customer */
        $customer = Guard::customer();
            $this->checkIsTrue($customer->isProviderTypeSoftware(), trans('admin.is_not_software_customer'));

        // 检测购买软件的客户开通账号数是否超过dev_acnt_num的数量
        $this->checkCanStoreNewAccount($customer);
            
        $device_account = $this->assembleDeviceAccount($request);

        $stored = DeviceAccount::create($device_account);

        return $this->response(compact('stored'));
    }
    
    /**
     * 普通客户 和 购买软件的客户 更新设备账号信息
     * @test
     *
     * @param  DeviceAccountUpdateRequest $request
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function update(DeviceAccountUpdateRequest $request, $id)
    {
        /** @var Customer $customer */
        $customer = Guard::customer();

        $this->checkIsTrue(
            ! $customer->isProviderType(Customer::PROVIDER_TYPE_VIRTUAL),
            trans('admin.is_virtual_provider')
        );

        // 超管才能操作的
        $this->checkIsTrue(CustomerAdmin::isGuardSuperAdmin(), trans('admin.is_super_man'));

        /** @var DeviceAccount $device_account */
        $device_account = DeviceAccount::where('customer_id', $customer->id)
            ->find($id);
        $this->checkItemExist($device_account, trans('admin.device_account'));
    
        $this->checkStoreIdValidate($request->store_id, $customer->id); // 可以取消，前端检测过了！
    
        $device_account_data = $this->assembleDeviceAccount($request);

        $updated = $device_account->update($device_account_data);

        return $this->response(compact('updated', 'device_account'));
    }

    /**
     * 启用和禁用设备账号
     * @test
     *
     * @param DeviceAccountPatchEnabledRequest $request
     * @param $id
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function patchEnabled(DeviceAccountPatchEnabledRequest $request, $id)
    {
        $customer_admin = Guard::customerAdmin();

        $this->checkIsTrue(
            ! $customer_admin->customer->isProviderType(Customer::PROVIDER_TYPE_VIRTUAL),
            trans('admin.is_virtual_provider')
        );

        // 超管才能操作的
        $this->checkIsTrue($customer_admin->isSuperMan(), trans('admin.is_super_man'));

        /** @var DeviceAccount $device_account */
        $device_account = (new DeviceAccount)
            ->where('customer_id', $customer_admin->customer_id)
            ->find($id);
        $this->checkItemExist($device_account, trans('admin.device_account'));

        $updated = $device_account->update([
            'enabled' => $request->enabled,
        ]);

        return $this->response(compact('updated', 'device_account'));
    }
    
    /**
     * @deprecated (已经放到上面了！)
     * 解除设备账号和设备的绑定
     *
     * Remove the specified resource from storage.
     *
     * @param  int $account_id
     *
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function unbindDevice($account_id)
    {
        // 超管才能操作的
        $this->checkIsTrue(CustomerAdmin::isGuardSuperAdmin(), '只有超管才能操作！');

        /** @var DeviceAccount $device_account */
        $device_account = DeviceAccount::find($account_id);
            $this->checkIsTrue($device_account, '此设备账号不存在！');

        $updated = $device_account->unbindDevice();

        return $this->response(compact('updated'));
    }

    /**
     * @param DeviceAccountStoreRequest|DeviceAccountUpdateRequest|Request $request
     * @return array
     */
    private function assembleDeviceAccount(Request $request)
    {
        $data = [
            'account'          => $request->account,
            'customer_id'      => Guard::customerAdmin()->customer_id,
            'store_id'         => $request->store_id ?? 0,
            'device_name'      => $request->device_name
        ];

        if ($request->password) {
            $data['password'] = $request->password;
            $data['password_modified_at'] = now();
        }

        return $data;
    }

    /**
     * @param $store_id
     * @param $customer_id
     *
     * @throws \Exception
     */
    private function checkStoreIdValidate($store_id, $customer_id)
    {
        if (! $store_id) {
            return;
        }

        $store = (new Store)->find($store_id);
            $this->checkItemExist($store, trans('admin.store'));
            $this->checkCanOperate(
                $store->customer_id === $customer_id,
                trans('admin.has_store')
            );
        
    }

    /**
     * @param Customer $customer
     * @throws \Exception
     */
    private function checkCanStoreNewAccount(Customer $customer)
    {
        $device_account_count = $customer->deviceAccounts()->count();

        $is_true = $customer->dev_acnt_num > (int)$device_account_count;

        $this->checkIsTrue($is_true, trans('admin.dev_acnt_num'));
    }
}
